import BpmnModeler from "@/module/main/other/BpmnTestView/BpmnModeler";
import {Component, ComponentProps, Hook, Mut, VueComponent} from "vue3-oop";
import {NButton, NCard, NForm, NFormItem, NGi, NGrid, NSpace, NTable, NTag, NInput,
  NSelect,NFormItemGi
} from "naive-ui";
import { nicon } from "@/utils/IconUtil";
import styles from "./index.module.scss";

interface IProps {
  bpmnModeler: BpmnModeler,
  elementId: string,
  elementName: string,
  elementType: string
}
@Component()
export default class Index extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    bpmnModeler: {default: {} as any},
    elementId: {default: ''},
    elementName: {default: ''},
    elementType: {default: ''}
  }

  public static tabKey = "LISTENERS"
  public static tabName = "执行监听器"

  @Mut() state = {
    listenerList: [] as any[]
  }

  private handleAddListener=()=>{
    const formData = ref({
      id:"",name:"",event:"",type:"",'class':'',expression:'',delegateExpression:'',
      scriptFormat:'',scriptType:'',inlineScript:'',externalScript:'',fields:[]
    }).value;
    const eventList = [{value:'start',label:'开始执行'},{value:'end',label:'结束执行'}]
    const typeList = [{value:'class',label:'Java 类'},{value:'expression',label:'表达式'},{value:'delegateExpression',label:'代理表达式'},{value:'script',label:'脚本'}]
    const scriptTypeList = [{value:'inlineScript',label:'内联脚本'},{value:'externalScript',label:'外部脚本'}]
    const handleConfirm=()=>{
      // if(this.state.signalList.find((msg)=>msg.id===formData.id)){
      //   window.$message.error("信号ID重复，无法添加");
      //   return;
      // }
      // const signal = this.props.bpmnModeler.getModdle().create('bpmn:Signal',{id: formData.id,name: formData.name});
      // this.props.bpmnModeler.getDefinitions().rootElements.push(signal)
      // this.loadDataFromElement();
    }
    const dialog = window.$popUp({
      style: {width:"900px",height:"500px"},
      content:()=>(
        <NCard title={`添加新监听器`}>
          {{
            default:()=>(
              <NGrid cols={1}>
                <NGi>
                  <NForm labelPlacement={"left"} labelWidth={100}>
                    <NGrid cols={2} xGap={10}>
                      <NFormItemGi label='监听器ID' required={true}><NInput value={formData.id} onUpdateValue={(value)=>{formData.id=value}} /></NFormItemGi>
                      <NFormItemGi label='监听器名称' required={true}><NInput value={formData.name} onUpdateValue={(value)=>{formData.name=value}} /></NFormItemGi>
                      <NFormItemGi label='监听的事件' required={true}><NSelect options={eventList} value={formData.event} onUpdateValue={(value)=>{formData.event=value}} /></NFormItemGi>
                      <NFormItemGi label='监听器类型' required={true}><NSelect options={typeList} value={formData.type} onUpdateValue={(value)=>{formData.type=value}} /></NFormItemGi>
                      {formData.type==='class'&&<NFormItemGi label='Java 类' required={true} span={2}><NInput value={formData.class} onUpdateValue={(value)=>{formData.class=value}} /></NFormItemGi>}
                      {formData.type==='expression'&&<NFormItemGi label='表达式' required={true} span={2}><NInput value={formData.expression} onUpdateValue={(value)=>{formData.expression=value}} /></NFormItemGi>}
                      {formData.type==='delegateExpression'&&<NFormItemGi label='代理表达式' required={true} span={2}><NInput value={formData.delegateExpression} onUpdateValue={(value)=>{formData.delegateExpression=value}} /></NFormItemGi>}
                      {formData.type==='script'&&<NFormItemGi label='脚本格式' required={true}><NInput value={formData.scriptFormat} onUpdateValue={(value)=>{formData.scriptFormat=value}} /></NFormItemGi>}
                      {formData.type==='script'&&<NFormItemGi label='脚本类型' required={true}><NSelect options={scriptTypeList} value={formData.scriptType} onUpdateValue={(value)=>{formData.scriptType=value}} /></NFormItemGi>}
                      {formData.type==='script'&&formData.scriptType==='inlineScript'&&<NFormItemGi label='内联脚本' required={true} span={2}><NInput value={formData.inlineScript} onUpdateValue={(value)=>{formData.inlineScript=value}} /></NFormItemGi>}
                      {formData.type==='script'&&formData.scriptType==='externalScript'&&<NFormItemGi label='外部脚本' required={true} span={2}><NInput value={formData.externalScript} onUpdateValue={(value)=>{formData.externalScript=value}} /></NFormItemGi>}
                    </NGrid>
                  </NForm>
                </NGi>
                <NGi>
                  <NTable striped size="small">
                    <thead>
                    <tr>
                      <th>序号</th>
                      <th>字段名称</th>
                      <th>字段类型</th>
                      <th>内容</th>
                      <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {formData.fields.map((field:any,index:number)=>(
                      <tr>
                        <td>{index+1}</td>
                        <td>{field.name}</td>
                        <td>{field.type}</td>
                        <td>{field.content}</td>
                        <td><NButton size="small" onClick={()=>{formData.fields.splice(index,1)}}>删除</NButton></td>
                      </tr>
                    ))}
                    </tbody>
                  </NTable>
                </NGi>
              </NGrid>
            ),
            footer:()=>(<NSpace>
              <NButton size={"small"} onClick={()=>{}}>添加参数</NButton>
              <NButton size={"small"} onClick={()=>{handleConfirm();dialog.destroy();}}>确定</NButton>
              <NButton size={"small"} onClick={()=>{dialog.destroy()}}>取消</NButton>
            </NSpace>)
          }}
        </NCard>
      )
    });
  }

  private handleRemoveListener=(index:number)=>{
    const { bpmnModeler } = this.props;
    const element = bpmnModeler.getSelectedElement();
    const { businessObject } = element;
    const { extensionElements } = businessObject;

    const listenerList = [] as any[];
    const extensionList = [] as any[];
    extensionElements?.values.forEach((el:any) => {
      const tmpList = (el.$type === 'flowable:ExecutionListener')?listenerList:extensionList;
      tmpList.push(el);
    });
    listenerList.splice(index,1);
    extensionList.push(...listenerList);
    const extensionElementsNew = bpmnModeler.getModdle().create('bpmn:ExtensionElements', {values: extensionList});
    bpmnModeler.getModeling().updateProperties(element,{extensionElements:extensionElementsNew});

    this.loadDataFromElement();
  }

  private loadDataFromElement=()=>{
    const { bpmnModeler } = this.props;
    const element = bpmnModeler.getSelectedElement();
    const { businessObject } = element;
    const { extensionElements } = businessObject;

    this.state.listenerList = [];
    extensionElements?.values.forEach((el:any) => {
      if (el.$type === 'flowable:ExecutionListener') {
        this.state.listenerList.push({
          ...el,
          listenerType: el.class?'Java 类':el.expression?'表达式':el.delegateExpression?'代理表达式':el.script?'脚本':''
        });
      }
    });
    // console.log(this.state.listenerList)
  }

  render(){
    this.loadDataFromElement();
    return(
      <NGrid cols={1} xGap={10}>
        <NGi>
          <NSpace style={{marginBottom:"5px",justifyContent:"space-between"}}>
            <NTag bordered={false} style={{fontSize:'16px'}} color={{color:'whitesmoke'}}>
              {{ avatar: nicon("FormatListBulletedSharp"), default: ()=>"执行监听器" }}
            </NTag>
            <NButton size="small" onClick={this.handleAddListener}>添加</NButton>
          </NSpace>
          <NTable striped size="small">
            <thead>
            <tr>
              <th>序号</th>
              <th>事件类型</th>
              <th>监听器类型</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {this.state.listenerList.map((item:any,index:number)=>(
              <tr>
                <td>{index+1}</td>
                <td>{item.event}</td>
                <td>{item.listenerType}</td>
                <td><NButton size="small" onClick={()=>{this.handleRemoveListener(index)}}>删除</NButton></td>
              </tr>
            ))}
            </tbody>
          </NTable>
        </NGi>
      </NGrid>
    )
  }
}